package com.benshou.bsoa.common.db;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.benshou.bsoa.common.trace.UserContext;
import jakarta.annotation.Resource;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.time.ZonedDateTime;
import java.util.Optional;

@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private IdentifierGenerator idGenerator;

    @Override
    public void insertFill(MetaObject metaObject) {
        var time = ZonedDateTime.now();
        this.strictInsertFill(metaObject, "createdTime", ZonedDateTime.class, time);
        this.strictInsertFill(metaObject, "updatedTime", ZonedDateTime.class, time);

        // 初始化用户
        var userId = getCurrentUserId();
        setFieldValByName("createdBy", userId, metaObject);
        setFieldValByName("updatedBy", userId, metaObject);

        // 设置初始值
        this.setFieldValByName("versionVal", BaseModel.INIT_VERSION_VAL, metaObject);
        this.setFieldValByName("recordInd", BaseModel.RecordIndEnum.ADDED.getValue(), metaObject);

        // 遍历实体类字段，查找带有 @BusinessId 注解的字段生成业务ID
        scanInitBusinessId(metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updatedTime", ZonedDateTime.class, ZonedDateTime.now());
        setFieldValByName("updatedBy", getCurrentUserId(), metaObject);
    }

    public void scanInitBusinessId(MetaObject metaObject) {
        // 遍历实体类字段，查找带有 @SnowflakeOrderNo 注解的字段
        ReflectionUtils.doWithFields(
                metaObject.getOriginalObject().getClass(),
                field -> Optional.ofNullable(field.getAnnotation(BusinessId.class))
                        .ifPresent(annotation -> {
                            // 生成雪花ID
                            Number snowflakeId = idGenerator.nextId(null);
                            // 构建业务ID号（如 RL202311011629）
                            String businessId = buildOrderNo(annotation, snowflakeId);
                            this.setFieldValByName(field.getName(), businessId, metaObject);
                        })
        );
    }

    private String buildOrderNo(BusinessId annotation, Number snowflakeId) {
        return String.format("%s%s",
                annotation.prefix(),
                snowflakeId
        );
    }

    /**
     * 获取当前的用户Id（包含默认值返回）
     *
     * @return 当前的用户Id
     */
    private String getCurrentUserId() {
        String userId = UserContext.getUserId();
        if (StringUtils.hasLength(userId)) {
            return userId;
        }

        return BaseModel.DEFAULT_USER;
    }
}